# encoding: utf-8
import zlib, hashlib
import simplejson as json
from django.http import HttpResponse
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
import datetime
import json
import time, re
import math

from app.config import server_config


class MiddlewareMixin(object):
    def __init__(self, get_response=None):
        self.get_response = get_response
        super(MiddlewareMixin, self).__init__()

    def __call__(self, request):
        response = None
        if hasattr(self, 'process_request'):
            response = self.process_request(request)
        if not response:
            response = self.get_response(request)
        if hasattr(self, 'process_response'):
            response = self.process_response(request, response)
        return response


class RbacMiddleware(MiddlewareMixin):
    """
    检查用户的url请求是否在其权限范围内
    """
    def process_request(self, request):

        remote_ip = request.META.get('REMOTE_ADDR')
        if server_config.get('is_ip_restrict') and remote_ip not in server_config.get('safe_ip'):
            return jsonify(code=403, success=False, msg=u"该IP无权限")
        path = request.path_info
        safe_url_flag = server_config.get('safe_url_flag')
        if not safe_url_flag:
            return jsonify(code=403, success=False, msg=u"url无权限")
        for item in safe_url_flag:
            if "login/" + item in path:
                return jsonify(code=403, success=False, msg=u"url invalid")
        # SAFE_URL = []
        # if path not in SAFE_URL:
        #     auth_status = request.session.get('username')
        #     if not auth_status:
        #         return jsonify(test={"code": 55}, success=False, msg=u"尚未登录，请先登录系统")

        return None


def datetime_handler(x):
    if isinstance(x, datetime.datetime):
        # return x.isoformat()
        return int(time.mktime(x.timetuple()))
    return None


def jsonify(*args, **kwargs):
    """
    通用返回json
    """
    # if 'test' in kwargs:
    #     del kwargs["test"]

    return HttpResponse(
        json.dumps(dict(*args, **kwargs), ensure_ascii=False, default=datetime_handler),
        content_type="application/json;charset = utf-8"
    )


def compress(str):
    """
    字符串压缩
    """
    str = str.strip()

    if str:
        if isinstance(str, unicode):
            return zlib.compress(str.encode("utf-8"), 9)

        return zlib.compress(str, 9)

    return ""


def dcompress(zstr):
    """
    字符串解压缩
    """
    if zstr:
        try:
            return zlib.decompress(zstr).strip()
        except Exception:
            return ""

    return ""


def isCharset(str, charset="utf-8"):
    """
    判断字符编码
    """
    return True


def humanReadableDate(datetime):
    """
    通用日期格式化:datetime
    """
    if not datetime:
        return ""

    format = "%Y-%m-%d %H:%M:%S"
    return datetime.strftime(format)


def humanDate(datetime):
    """
    通用日期格式化:date
    """
    if not datetime:
        return ""

    format = "%Y-%m-%d"
    return datetime.strftime(format)


def query(params, model):
    """
    通用条件查询
    """
    pass


def pageslist(datas, num, page):
    """
    分页显示
    :param datas: 分页的所有数据，列表格式
    :param page: 要展示的页数
    :param num: 每页展示的数量
    :return:
    """
    paginator = Paginator(list(datas), num)  # num为每页显示的数量
    Totalcount = paginator.count  # 获取记录总数
    Totalpages = paginator.num_pages  # 获取总页数
    try:
        contacts = paginator.page(int(page)).object_list  # page为url中传入的页数
    except PageNotAnInteger:
        contacts = paginator.page(1).object_list
    except EmptyPage:
        contacts = paginator.page(paginator.num_pages).object_list
    # print contacts
    data = {"Total": Totalcount, "Infos": contacts, "Totalpages": Totalpages}
    return data


def pages_limit_list(datas, total, nums):
    """
    django mysql limit分页
    :param datas:
    :param total:
    :return:
    """
    total_pages = math.ceil(total / nums)
    info = {}

    info['Infos'] = list(datas)
    info['Total'] = total
    info['Totalpages'] = total_pages

    return info


def mypaginator(params, dataList):
    """
    通用分页
    """
    if "page" in params and params["page"]:
        page = params.get("page")
    else:
        page = 1
    if "pageSize" in params and params["pageSize"]:
        pageSize = params.get("pageSize")
    else:
        pageSize = 10

    paginator = Paginator(dataList, pageSize)

    try:
        lst = paginator.page(page)
    except PageNotAnInteger:
        lst = paginator.page(1)
    except EmptyPage:
        lst = paginator.page(paginator.num_pages)

    return {
        "dataList": list(lst.object_list),
        "totalCount": paginator.count,
        "totalPages": paginator.num_pages,
        "pageNum": lst.number,
        "nextPageNum": lst.next_page_number() if lst.has_next() else paginator.num_pages,
        "prevPageNum": lst.previous_page_number() if lst.has_previous() else lst.start_index()
    }


def checklen(pwd):
    return len(pwd) >= 8


def checkContainUpper(pwd):
    pattern = re.compile('[A-Z]+')
    match = pattern.findall(pwd)
    if match:
        return True
    else:
        return False


def checkContainNum(pwd):
    pattern = re.compile('[0-9]+')
    match = pattern.findall(pwd)
    if match:
        return True
    else:
        return False


def checkContainLower(pwd):
    pattern = re.compile('[a-z]+')
    match = pattern.findall(pwd)
    if match:
        return True
    else:
        return False


def checkSymbol(pwd):
    pattern = re.compile('([^a-z0-9A-Z])+')
    match = pattern.findall(pwd)
    if match:
        return True
    else:
        return False


def check_passwd(pwd):
    # 判断密码长度是否合法
    lens = checklen(pwd)
    # 判断是否包含大写字母
    upper = checkContainUpper(pwd)
    # 判断是否包含小写字母
    lower = checkContainLower(pwd)
    # 判断是否包含数字
    num = checkContainNum(pwd)
    # 判断是否包含符号
    symbol = checkSymbol(pwd)
    return lens and upper and lower and num and symbol


def encrypt(pwd):
    """
    加密函数
    """
    return hashlib.md5(pwd).hexdigest().upper()
